package cn.iocoder.yudao.module.trade;


import cn.hutool.core.util.RandomUtil;
import cn.hutool.extra.template.Template;
import cn.hutool.extra.template.TemplateConfig;
import cn.hutool.extra.template.TemplateEngine;
import cn.hutool.extra.template.TemplateUtil;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ThreadLocalRandom;

/**
 * 打印小票测试类
 */
public class TestMain {


    public static final String URL = "http://api.feieyun.cn/Api/Open/";//不需要修改

    public static final String USER = "379955647@qq.com";//*必填*：账号名
    public static final String UKEY = "4E8cavsn8yLfzT2R";//*必填*: 飞鹅云后台注册账号后生成的UKEY 【备注：这不是填打印机的KEY】
    public static final String SN = "960248494";//*必填*：打印机编号，必须要在管理后台里添加打印机或调用API接口添加之后，才能调用API


    public static void main(String[] args) {

        LocalDateTime localDateTime = LocalDateTime.now();
        System.out.println("localDateTime:" + localDateTime);

        // 本方法中仅举例一个简短的测试用例
        Timer timer = new Timer();
        timer.start();
        // 计算一个复杂的数学运算
        for (int i=0;i<100000;i++){
            int hour = RandomUtil.randomInt(14, 18);
            int min = RandomUtil.randomInt(1, 59);
            int sen = RandomUtil.randomInt(1, 59);
            //System.out.println(String.format("hour:%s,min:%s,sen:%s",hour,min,sen));
            LocalDateTime dateTime = localDateTime.withHour(hour).withMinute(min).withSecond(sen);
        }
        timer.end();
        System.out.println("---1---计算时间：" + timer.getElapsedTime() + " 毫秒");

        timer.start();
        getRandomDateTimeTest();
        timer.end();
        System.out.println("---2---计算时间：" + timer.getElapsedTime() + " 毫秒");

        // 打印小票
        //print("961804428");

        // 获取当前时间
        timer.start();
        // 计算一个复杂的数学运算
        for (int i=0;i<100000;i++){
            int hour = RandomUtil.randomInt(14, 18);
            int min = RandomUtil.randomInt(1, 59);
            int sen = RandomUtil.randomInt(1, 59);
            //System.out.println(String.format("hour:%s,min:%s,sen:%s",hour,min,sen));
            LocalDateTime dateTime = LocalDateTime.of(localDateTime.getYear(), localDateTime.getMonthValue(), localDateTime.getDayOfMonth(), hour, min, sen);
            String formatDateTime = dateTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
            System.out.println(formatDateTime);
        }
        timer.end();
        System.out.println("---3---计算时间：" + timer.getElapsedTime() + " 毫秒");

        LocalDateTime dateTime = LocalDateTime.now();
        String formatDateTime = dateTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));


        // 创建一个集合并初始化

        List<Map<String, Object>> list = new ArrayList<>();







//        String resultStr = testBt();
//        printLabelMsg(SN,resultStr);
//        String str = "养生奶茶大杯/常温/少糖西红柿蛋炒饭真的好喝啊";
//        String formattedStr = String.format("%-5s", str);
//        System.out.println(formattedStr+"#");
//        String resultStr = formattedStr + "12<BR>";
//        str = "滋阴养肾好茶大杯/常温/少糖";
//        formattedStr = String.format("%-5s", str);
//        System.out.println(formattedStr+"#");
        //print("961804428");
//        testList();
        // receipt 小票
//        Integer price = 1;
//        DecimalFormat df = new DecimalFormat("0.00");
//        // 使用 DecimalFormat 格式化
//        double num = price/100;
//        System.out.println("num：" + num);
//        String totalAmount = MoneyUtils.fenToYuanStr(price);
//        System.out.println("totalAmount：" + totalAmount);
    }

    public static class Timer {
        // 记录开始时间
        private long startTime;
        // 记录结束时间
        private long endTime;

        // 构造器
        public Timer() {
            startTime = System.currentTimeMillis();
        }

        // 开始计时
        public void start() {
            startTime = System.currentTimeMillis();
        }

        // 结束计时
        public void end() {
            endTime = System.currentTimeMillis();
        }

        // 计算方法执行时间
        public long getElapsedTime() {
            return endTime - startTime;
        }
    }


    // 使用 java.time.LocalDateTime 类来生成随机时间
    public static LocalDateTime getRandomDateTime(LocalDateTime startDateTime, LocalDateTime endDateTime) {
        // 获取开始时间和结束时间的毫秒值
        long startMillis = startDateTime.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli();
        long endMillis = endDateTime.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli();

        for (int i=0;i<100000;i++) {
            // 生成随机时间
            long randomMillis = ThreadLocalRandom.current().nextLong(startMillis, endMillis + 1);
            LocalDateTime localDateTime = LocalDateTime.ofInstant(Instant.ofEpochMilli(randomMillis), ZoneId.systemDefault());
        }

        // 将随机时间转换为 LocalDateTime 对象
        return null;
    }

    // 测试生成随机时间的方法
    public static void getRandomDateTimeTest() {
        // 本方法中仅举例一个简短的测试用例
        LocalDateTime startDateTime = LocalDateTime.of(2024, 4, 2, 14, 0);
        LocalDateTime endDateTime = LocalDateTime.of(2024, 4, 2, 18, 59, 59);
        LocalDateTime randomDateTime = getRandomDateTime(startDateTime, endDateTime);

        //System.out.println("---- " + randomDateTime);
    }

    private static String print(String sn) {
        //标签说明：
        //单标签:
        //"<BR>"为换行,"<CUT>"为切刀指令(主动切纸,仅限切刀打印机使用才有效果)
        //"<LOGO>"为打印LOGO指令(前提是预先在机器内置LOGO图片),"<PLUGIN>"为钱箱或者外置音响指令
        //成对标签：
        //"<CB></CB>"为居中放大一倍,"<B></B>"为放大一倍,"<C></C>"为居中,<L></L>字体变高一倍
        //<W></W>字体变宽一倍,"<QR></QR>"为二维码,"<BOLD></BOLD>"为字体加粗,"<RIGHT></RIGHT>"为右对齐
        //拼凑订单内容时可参考如下格式
        //根据打印纸张的宽度，自行调整内容的格式，可参考下面的样例格式

        String content;
        content = "<CB>万民匠心养生茶</CB><BR>";
        content += "<C><BOLD>销售单</BOLD></C><BR>";
        content += "店铺名称：正荣中心店<BR>";
        content += "订单号：o202402011741111<BR>";
        content += "下单时间：2023-01-01 12:21:21<BR>";
        content += "取餐类型：自提<BR><BR>";
        content += "名称　　　　　              数量<BR>";
        content += "--------------------------------<BR>";
        content += "养生奶茶  大杯/常温/少糖    10<BR>";
        content += "滋阴养肾好茶  大杯/常温/少糖    1<BR>";
        content += "养生奶茶  大杯/常温/少糖    3<BR>";
        content += "名称　　　　　          数量<BR>";
        content += "--------------------------------<BR>";
        content += "养生奶茶（大杯/常温/少糖 ）     1<BR>";
        content += "滋阴养肾好茶（大杯/常温/少糖）   1<BR>";
        content += "养生奶茶（大杯/常温/少糖）      12<BR>";
        content += "鸡蛋炒饭（）　                100<BR>";
        content += "番茄蛋炒饭                   100.0<BR>";
        content += "番茄蛋炒饭　　                100.0<BR>";
        content += "西红柿蛋炒饭　                100.0<BR>";
        String str = "养生奶茶大杯/常温/少糖西红柿蛋炒饭真的好喝啊";
        String formattedStr = String.format("%-15s", str);
        System.out.println(formattedStr);
        String resultStr = formattedStr + "12<BR>";
        content += resultStr;
        str = "滋阴养肾好茶大杯/常温/少糖";
        formattedStr = String.format("%-15s", str);
        System.out.println(formattedStr);
        resultStr = formattedStr + "120<BR>";
        content += resultStr;
        content += "西红柿鸡蛋炒饭                100.0<BR>";
        content += "备注：少少少冰<BR>";
        content += "--------------------------------<BR>";
        content += "总金额：299.13元<BR>";
        content += "优惠金额：100.00元<BR>";
        content += "实付金额：199.13元<BR>";
        content += "付款方式：微信支付<BR>";
        content += "<QR>http://www.dzist.com</QR>";


        System.out.println(content);

        //通过POST请求，发送打印信息到服务器
        RequestConfig requestConfig = RequestConfig.custom()
                .setSocketTimeout(30000)//读取超时
                .setConnectTimeout(30000)//连接超时
                .build();

        CloseableHttpClient httpClient = HttpClients.custom()
                .setDefaultRequestConfig(requestConfig)
                .build();

        HttpPost post = new HttpPost(URL);
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add(new BasicNameValuePair("user", USER));
        String STIME = String.valueOf(System.currentTimeMillis() / 1000);
        nvps.add(new BasicNameValuePair("stime", STIME));
        nvps.add(new BasicNameValuePair("sig", signature(USER, UKEY, STIME)));
        nvps.add(new BasicNameValuePair("apiname", "Open_printMsg"));//固定值,不需要修改
        nvps.add(new BasicNameValuePair("sn", sn));
        nvps.add(new BasicNameValuePair("content", content));
        nvps.add(new BasicNameValuePair("times", "1"));//打印联数

        CloseableHttpResponse response = null;
        String result = null;
        try {
            post.setEntity(new UrlEncodedFormEntity(nvps, "utf-8"));
            response = httpClient.execute(post);
            int statecode = response.getStatusLine().getStatusCode();
            if (statecode == 200) {
                HttpEntity httpentity = response.getEntity();
                if (httpentity != null) {
                    //服务器返回的JSON字符串，建议要当做日志记录起来
                    result = EntityUtils.toString(httpentity);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (response != null) {
                    response.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                post.abort();
            } catch (Exception e) {
                e.printStackTrace();
            }
            try {
                httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;

    }


    //方法2
    private static String printLabelMsg(String sn, String printStr) {

//        String code = "9999";
//        String content;
//        content = "<DIRECTION>1</DIRECTION>";//设定打印时出纸和打印字体的方向，n 0 或 1，每次设备重启后都会初始化为 0 值设置，1：正向出纸，0：反向出纸，
//        content += "<TEXT x='9' y='10' font='12' w='1' h='2' r='0'> "+code+"       自提      第1/3杯</TEXT><TEXT x='80' y='80' font='12' w='2' h='2' r='0'>可乐鸡翅</TEXT><TEXT x='9' y='180' font='12' w='1' h='1' r='0'>张三先生       13800138000</TEXT>";//40mm宽度标签纸打印例子，打开注释调用标签打印接口打印
//
//
//        String testStr = "<DIRECTION>1</DIRECTION>\n" +
//                "<TEXT x='9' y='10' font='12' w='1' h='1' r='0'>#9999     自提    第2/3杯</TEXT>\n" +
//                "<TEXT x='9' y='50' font='12' w='1' h='2' r='0'>滋阴补血茶</TEXT>\n" +
//                "<TEXT x='9' y='109' font='12' w='1' h='1' r='0'>大杯/常温/少糖</TEXT>\n" +
//                "<TEXT x='9' y='155' font='12' w='1' h='1' r='0'>2024/01/01 11:25</TEXT>\n" +
//                "<TEXT x='9' y='190' font='12' w='1' h='1' r='0'>建议尽快使用，效果更佳！</TEXT>";
        String content = printStr;
        System.out.println(content);
        //通过POST请求，发送打印信息到服务器
        RequestConfig requestConfig = RequestConfig.custom()
                .setSocketTimeout(30000)//读取超时
                .setConnectTimeout(30000)//连接超时
                .build();

        CloseableHttpClient httpClient = HttpClients.custom()
                .setDefaultRequestConfig(requestConfig)
                .build();

        HttpPost post = new HttpPost(URL);
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add(new BasicNameValuePair("user", USER));
        String STIME = String.valueOf(System.currentTimeMillis() / 1000);
        nvps.add(new BasicNameValuePair("stime", STIME));
        nvps.add(new BasicNameValuePair("sig", signature(USER, UKEY, STIME)));
        nvps.add(new BasicNameValuePair("apiname", "Open_printLabelMsg"));//固定值,不需要修改
        nvps.add(new BasicNameValuePair("sn", sn));
        nvps.add(new BasicNameValuePair("content", content));
        nvps.add(new BasicNameValuePair("times", "1"));//打印联数

        CloseableHttpResponse response = null;
        String result = null;
        try {
            post.setEntity(new UrlEncodedFormEntity(nvps, "utf-8"));
            response = httpClient.execute(post);
            int statecode = response.getStatusLine().getStatusCode();
            if (statecode == 200) {
                HttpEntity httpentity = response.getEntity();
                if (httpentity != null) {
                    //服务器返回的JSON字符串，建议要当做日志记录起来
                    result = EntityUtils.toString(httpentity);
                    System.out.println("result:" + result);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (response != null) {
                    response.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                post.abort();
            } catch (Exception e) {
                e.printStackTrace();
            }
            try {
                httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;

    }

    //生成签名字符串
    private static String signature(String USER, String UKEY, String STIME) {
        String s = DigestUtils.sha1Hex(USER + UKEY + STIME);
        return s;
    }


    public static String testBt() {
        String testStr = "<DIRECTION>1</DIRECTION>" +
                "<TEXT x='9' y='10' font='12' w='1' h='1' r='0'>#${code}   ${type}   第${index}杯</TEXT>" +
                "<TEXT x='9' y='50' font='12' w='1' h='2' r='0'>${name}</TEXT>" +
                "<TEXT x='9' y='109' font='12' w='1' h='1' r='0'>${sku}</TEXT>" +
                "<TEXT x='9' y='155' font='12' w='1' h='1' r='0'>${createTime}</TEXT>" +
                "<TEXT x='9' y='190' font='12' w='1' h='1' r='0'>${footer}</TEXT>";

        System.out.println(testStr);
        //自动根据用户引入的模板引擎库的jar来自动选择使用的引擎
        //TemplateConfig为模板引擎的选项，可选内容有字符编码、模板路径、模板加载方式等，默认通过模板字符串渲染
        TemplateEngine engine = TemplateUtil.createEngine(new TemplateConfig());
        String code = "1001";
        String type = "自提";
        String index = "1/2";
        String name = "养生茶";
        String sku = "大杯/常温/少糖";
        String createTime = "2024-04-01 12:03";
        String footer = "建议尽快使用，效果更佳！";
        Map<String, String> map = new HashMap<String, String>();
        map.put("code", code);
        map.put("type", type);
        map.put("index", index);
        map.put("name", name);
        map.put("sku", sku);
        map.put("createTime", createTime);
        map.put("footer", footer);

        //假设我们引入的是Beetl引擎，则：
        Template template = engine.getTemplate(testStr);
        //Dict本质上为Map，此处可用Map

        String result = template.render(map);
        //输出：Hello Hutool
        System.out.println(result);
        return result;
    }


    public static void testList() {

        int all_count = 4;
        int sub_index = 1;
        for (int i = 0; i < 2; i++) {

            Integer count = 2;
            // 同一个sku购买多个
            for (int j = 0; j < count; j++) {
                String str_index = sub_index + "/" + all_count;
                System.out.println(str_index);
                sub_index++;
            }
        }
    }

}
